﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

using System.Net;
using System.Net.Http;
using System.Collections.ObjectModel;
namespace WebCamStream.DataModel
{
    public class JsonToGridFormatDataAccess
    {
        private static JsonToGridFormatDataAccess _JsonDataSource = new JsonToGridFormatDataAccess();
        private static ObservableCollection<EnityFormat> _items = new ObservableCollection<EnityFormat>();
        public ObservableCollection<EnityFormat> Items
        {
            get { return _items; }


        }
        public static IEnumerable<EnityFormat> GetGroups(string uniqueId)
        {
            if (!uniqueId.Equals("1")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");
            var d = _JsonDataSource.Items.Where(x => x.GroupId.Equals("1", StringComparison.CurrentCultureIgnoreCase));
            return d;
        }
       
        public const string ReplaceDateFormatInJson = @"\\/Date\((\d+)\+\d+\)\\/";
        public const string RestApiUrl = "http://caymayapi.azurewebsites.net/api/getItems?groupid=1&offset=0&limit=5";
        public static async Task LoadLocalDataAsync()
        {
            // Retrieve recipe data from Recipes.txt          

            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(RestApiUrl);
            response.EnsureSuccessStatusCode();
            // var result = await FileIO.ReadTextAsync(file);
            ConvertJsonToGenericList(await response.Content.ReadAsStringAsync(), "Result");

        }
        public static string DateReplaceinJsonData(string jsonData)
        {
            string result = string.Empty;
            try
            {
                var matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                var reg = new Regex(ReplaceDateFormatInJson);
                result = reg.Replace(jsonData, matchEvaluator);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return result;
        }
        // date format for json date
        public static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            try
            {

                var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
                // var dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
                dt = dt.ToLocalTime();
                result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return result;
        }
        public static void ConvertJsonToGenericList(string json, string jsonResultName)
        {
            try
            {
                var jArray = JArray.Parse(json);
                //JObject o = JObject.Parse(json);
                foreach (EnityFormat data in JsonConvert.DeserializeObject<List<EnityFormat>>(jArray.ToString()))
                {
                    _JsonDataSource.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


    }
    //public class JsonDataGroup
    //{
    //    private ObservableCollection<EnityFormat> _items = new ObservableCollection<EnityFormat>();
    //    public ObservableCollection<EnityFormat> Items
    //    {
    //        get { return this._items; }
    //    }

    //    public IEnumerable<EnityFormat> TopItems
    //    {

    //        get { return this._items.Take(3); }
    //    }
    //    private string _title;

    //    public string Title
    //    {
    //        get
    //        {               

    //            return this._title;
    //        }
    //        set
    //        {
    //            this._title = "Group 1";               
    //        }
    //    }




    //}

    public class EnityFormat
    {
        public string ItemId { get; set; }
        public string Version { get; set; }
        public string ParentId { get; set; }
        public string OrderNo { get; set; }
        public string ThumbnailUrl { get; set; }
        public string VideoUrl { get; set; }
        public string Title { get; set; }
        public string SubTitle { get; set; }
        public string Description { get; set; }
        public string ItemLevel { get; set; }
        public string TotalViews { get; set; }
        public string TotalWatches { get; set; }
        public string Price { get; set; }
        public DateTime CreationDatetime { get; set; }
        public DateTime ModifyDatetime { get; set; }
        public string OwnerName { get; set; }
        public string OwnerId { get; set; }
        public string PrevOwnerId { get; set; }
        public string PrivacySettings { get; set; }
        public string Ranking { get; set; }
        public string OriginalVersionId { get; set; }
        public string TotalTime { get; set; }
        public string GroupId { get; set; }
        public string BackGroundImage { get; set; }
        public string ResourceId { get; set; }
        public string Source { get; set; }
        public string Live { get; set; }
        public string Visits { get; set; }
        public string IsLeaf { get; set; }
        public bool? Status { get; set; }
    }
}
